/**
 * @(#)HomeController.java
 * Description:
 * Version :	1.0
 * Copyright:	Copyright (c) 苗方清颜 版权所有
 */
package pub.lichao.test.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * 分布式锁测试类
 */
@Controller
public class DistributedLockController {
    @Autowired
    private DistributedLock distributedLock;

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(){
        return "/index";
    }

    @RequestMapping(value = "/occupyDistributedLock", method = RequestMethod.GET)
    public String occupyDistributedLock(RedirectAttributes redirectAttributes, HttpServletRequest request){
        String key = "userid:55689";

        String lockId = null;
        try{
            //占用锁
            lockId = distributedLock.occupyDistributedLock(key);
            if(lockId != null){
                //程序执行
                TimeUnit.SECONDS.sleep(10);
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //释放锁
            distributedLock.releaseDistributedLock(key,lockId);
        }
        redirectAttributes.addFlashAttribute("lockId",lockId);

        return "redirect:/";
    }
}
